class UsersController < ApplicationController
  before_filter :check_root,      :only => [:make_moderator, :remove_moderator]
  
  after_filter  :store_location,  :only => [:show]
  
  # render new.rhtml
  def new
    @user = User.new
  end
  
  def index
    @users = User.find(:all)
  end
  
  def make_moderator
    @user = User.find(params[:id])
    @user.moderator = true
    if @user.save
      flash[:notice] = "#{@user.login} is now a moderator."
      redirect_back_or_default(user_url(@user))
    else
      flash[:notice] = "Didn't work."
      redirect_back_or_default(user_url(@user))
    end
  end
  
  def remove_moderator
    @user = User.find(params[:id])
    @user.moderator = false
    if @user.save
      flash[:notice] = "#{@user.login} is not a moderator."
      redirect_back_or_default(user_url(@user))
    else
      flash[:notice] = "Didn't work."
      redirect_back_or_default(user_url(@user))
    end
  end
    
  def show
    @user = User.find(params[:id])
  end
 
  def create
    logout_keeping_session!
    @user = User.new(params[:user])
    @user.moderator = true if @user.login.eql?("root")
    success = @user && @user.save
    if success && @user.errors.empty?
      # Protects against session fixation attacks, causes request forgery
      # protection if visitor resubmits an earlier form using back
      # button. Uncomment if you understand the tradeoffs.
      # reset session
      self.current_user = @user # !! now logged in
      redirect_back_or_default('/')
      flash[:notice] = "Thanks for signing up!"
    else
      flash[:error]  = "We couldn't set up that account, sorry.  Please try again, or contact an admin (link is above)."
      render :action => 'new'
    end
  end
  
  protected
  
  def check_root
    if !(logged_in? && current_user.login.eql?("root"))
      flash[:notice] = "You can't do that."
      redirect_back_or_default('/')
    end
  end
end
